// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;
import Item from './item'
@ccclass
export default class Main extends cc.Component {

    @property(cc.Node)
    rectNode: cc.Node = null;

    @property
    text: string = 'hello';

    @property(cc.Layout)
    itemLayout = null

    @property(cc.Prefab)
    block = null

    isDrawing = false

    startPoint = null

    endPoint = null

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.initBlocks();
        this.isDrawing = false; // 是否正在绘制矩形
        this.startPoint = cc.v2(0, 0); // 矩形起点
        this.endPoint = cc.v2(0, 0); // 矩形终点

        this.rectNode.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.rectNode.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.rectNode.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);


        // 开启物理引擎
        cc.director.getPhysicsManager().enabled = true;

        // 设置物理引擎的调试绘制
        cc.director.getPhysicsManager().debugDrawFlags =
            cc.PhysicsManager.DrawBits.e_aabbBit |
            cc.PhysicsManager.DrawBits.e_pairBit |
            cc.PhysicsManager.DrawBits.e_centerOfMassBit |
            cc.PhysicsManager.DrawBits.e_jointBit |
            cc.PhysicsManager.DrawBits.e_shapeBit;

        // 设置物理引擎的重力
        cc.director.getPhysicsManager().gravity = cc.v2(0, -320);
    }
    onTouchStart(event) {
        this.isDrawing = true;
        this.startPoint = this.rectNode.convertToNodeSpaceAR(event.getLocation());
        this.endPoint = this.startPoint;
    }

    onTouchMove(event) {
        if (this.isDrawing) {
            this.endPoint = this.rectNode.convertToNodeSpaceAR(event.getLocation());
            this.drawRectangle();
        }
    }

    onTouchEnd(event) {
        if (this.isDrawing) {
            this.endPoint = this.rectNode.convertToNodeSpaceAR(event.getLocation());
            this.checkSum();
            this.isDrawing = false;
            this.startPoint = cc.v2(0, 0);
            this.endPoint = cc.v2(0, 0);
            this.rectNode.getComponent(cc.Graphics).clear();
        }
    }

    drawRectangle() {
        let graphics = this.rectNode.getComponent(cc.Graphics);
        graphics.clear();
        graphics.rect(this.startPoint.x, this.startPoint.y, this.endPoint.x - this.startPoint.x, this.endPoint.y - this.startPoint.y);
        graphics.stroke();
        graphics.fill();
    }

    checkSum() {

        // graphics的rect无法转为世界坐标，借助一个中间节点来完成这个事情
        let graphicsNode = new cc.Node()
        graphicsNode.parent = this.rectNode;

        let width = Math.abs(this.endPoint.x - this.startPoint.x);
        let height = Math.abs(this.endPoint.y - this.startPoint.y);
        let x = Math.min(this.startPoint.x, this.endPoint.x);
        let y = Math.min(this.startPoint.y, this.endPoint.y);

        graphicsNode.width = width;
        graphicsNode.height = height;
        graphicsNode.position = cc.v3(x + width / 2, y + height / 2, 0);

        // 获取矩形框的位置和尺寸
        let rectBoundingBox = graphicsNode.getBoundingBoxToWorld();
        let res = []
        // 遍历判断是否相交，理论还能优化下，距离很远的是直接跳过
        this.itemLayout.node.children.forEach((element: cc.Node)=> {
            let childBox = element.getBoundingBoxToWorld();
            // 判断矩形框与精灵是否相交
            if(rectBoundingBox.intersects(childBox)){
                // console.log("矩形框与精灵相交！");
                res.push(element)
            } else {
                // console.log("矩形框与精灵不相交。", childBox);
            }
        })
        let sum = 0
        // 数字加和
        res.forEach((element: cc.Node) => {
            let item = element.getComponent(Item);
            sum += parseInt(item.text);
        });
        // 刚好等于10 就移除子节点
        if(sum === 10){
            while(res.length){
                let element = res.pop();
                element.removeFromParent();
            }
        }
        graphicsNode.removeFromParent()
        graphicsNode = null;
    }

    start() {

    }
    isGameEnd(){
        // 倒计时逻辑，倒计时结束，游戏结束
    }
    initBlocks() {
        this.itemLayout.enabled = true;
        // 节点数量自定义
        for (let index = 0; index < 176; index++) {
            let block = cc.instantiate(this.block)
            block.parent = this.itemLayout.node
        }
        this.itemLayout.updateLayout()
        this.itemLayout.enabled = false; // 关闭布局，否则会闪烁
    }
    update (dt) {
        if(this.itemLayout.node.children.length < 1){
            console.log('顺利过关了')
            return
        }
        this.isGameEnd()
    }
}
